package com.sky.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.result.Result;
import com.sky.service.user.ShoppingCartService;
import com.sky.utils.RedisCleanCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper mapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisCleanCacheUtil cleanCacheUtil;

    @Override
    @Transactional
    public void addShoppingCartItem(ShoppingCartDTO dto) {
        log.info("ShoppingCartDTO：{}", dto);
        // 拷贝dto数据
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto, shoppingCart);
        // 设置当前用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(shoppingCart.getUserId() != null, ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .eq(shoppingCart.getDishFlavor() != null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());


        // 根据dto数据和当前用户id获取到商品信息
        ShoppingCart cart = mapper.selectOne(wrapper);

        // 判断该商品是否为重复购买
        if (cart != null) {
            // 重复购买，更改购买数量
            LambdaUpdateWrapper<ShoppingCart> updateWrapper = new LambdaUpdateWrapper<>();
            cart.setNumber(cart.getNumber() + 1);
            updateWrapper
                    .eq(ShoppingCart::getId, cart.getId())
                    .set(ShoppingCart::getNumber, cart.getNumber());
            mapper.update(null, updateWrapper);
        } else {
            //判断当前添加到购物车的是菜品还是套餐
            Long dishId = shoppingCart.getDishId();
            // 如果是菜品
            if (dishId != null) {
                // 根据该商品关联的菜品id查询菜品信息
                LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishLambdaQueryWrapper.eq(Dish::getId, dishId);
                Dish dish = dishMapper.selectOne(dishLambdaQueryWrapper);

                // 设置对应参数
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());

            } else {
                // 根据商品关联套餐id 查询对应套餐信息
                LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                setmealLambdaQueryWrapper.eq(Setmeal::getId, shoppingCart.getSetmealId());
                Setmeal setmeal = setmealMapper.selectOne(setmealLambdaQueryWrapper);

                // 设置对应参数
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }

//            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            // 插入数据
            mapper.insert(shoppingCart);
        }

    }

    @Override
    public Result<List<ShoppingCart>> getShoppingCartItems(Long userId) {
        List<ShoppingCart> list = mapper.getShoppingCartItems(userId);
//        list.forEach(e -> {
//            e.setAmount(e.getAmount().multiply(BigDecimal.valueOf(e.getNumber())));
//        });

        return Result.success(list);
    }

    @Override
    @Transactional
    public Result<Object> cleanShoppingCart(Long userId) {
        mapper.cleanShoppingCart(userId);
        return Result.success(userId);

    }

    @Override
    @Transactional
    public Result<Object> subShoppingCartByUserId(ShoppingCartDTO dto, Long userId) {
        // 拷贝dto数据
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto, shoppingCart);
        shoppingCart.setUserId(userId);

        // 根据dto数据获取对应商品
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper
                .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .eq(shoppingCart.getDishFlavor() != null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());

        // 根据dto数据获取对应商品
        ShoppingCart searchedShoppingCart = mapper.selectOne(shoppingCartLambdaQueryWrapper);

        // 判断该商品是否存在?
        // 前端传递的数据对应的商品一定是存在的，如果不存在，证明其购物车走的是错误的缓存，写出bug了得去修

        if (searchedShoppingCart == null) return Result.error("后台数据错误,请稍后再试");

        // 判断该商品的件数是否为一
        if (searchedShoppingCart.getNumber() == 1) {
            // 件数为一,直接删除该商品
            mapper.removeShoppingCartItem(searchedShoppingCart);
        } else {
            // 件数不为一，减少件数
            searchedShoppingCart.setNumber(searchedShoppingCart.getNumber() - 1);
            LambdaUpdateWrapper<ShoppingCart> shoppingCartLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            shoppingCartLambdaUpdateWrapper
                    .set(ShoppingCart::getNumber, searchedShoppingCart.getNumber())
                    .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                    .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                    .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                    .eq(shoppingCart.getDishFlavor() != null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());

            mapper.update(null, shoppingCartLambdaUpdateWrapper);
        }

        return Result.success();
    }
}
